package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.Arrays;

@RestController
@RequestMapping("/request")
public class RequestController {
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        // 获取所有 Cookie 信息
        Cookie[] cookies = request.getCookies();
        Arrays.stream(cookies).forEach(x-> {
            System.out.println(x.getName() + ": " + x.getValue());
        });
        // 等价
        for (Cookie c : cookies) {
            System.out.println(c.getName() + ": " + c.getValue());
        }

        return "";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("frost") String frost, @CookieValue("cold") String cold) {
        // 获取一些 Cookie
        return "frost: " + frost;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("username", "zhangsan");
        return "设置session成功";
    }

    @RequestMapping("/getSession")
    public String getSession1(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        return "登录用户: " + username;
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        String username = (String)session.getAttribute("username");
        return "登录用户: " + username;
    }

    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("username") String username) {
        return "登录用户: " + username;
    }

    @RequestMapping("/getSession4")
    public String getSession4(@SessionAttribute(value = "username", required = false) String username) {
        return "登录用户: " + username;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        return userAgent;
    }

}
